#!/usr/bin/python
# -*- coding:utf-8 -*-
#登录
import logging
logging.basicConfig(level=20,
                    format='%(module)s - %(asctime)s - %(levelname)s :  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    handlers=[logging.FileHandler('account.log',encoding='utf-8',mode='a')]
                    )
dic_state = {'user_login_state':False,'username':None}
def auth(func):
    def wrapper(*args,**kwargs):
        if dic_state['user_login_state'] == True :
            func(dic_state['username'],**kwargs)
        else:
            with open('atm_user_info', 'r', encoding='utf-8')as f:
                date = f.read()
                date1 = date.split("\n")#dodo|000000    meme|111111
            state=0
            while state<3:
                account = input("请输入账户名称：")
                account_pwd = input("请输入账户密码：")
                for i in date1:
                    user_info = i.split('|')
                    if account == user_info[0] and account_pwd == user_info[1]:
                        func(account,**kwargs)
                        dic_state['user_login_state']=True
                        dic_state['username']='dodo'
                        return account
                        break
                else:
                    print("用户名或密码错误，请重新输入！")
                    state+=1
                    if state == 3:
                        print("登录失败！")
                        logging.info("%s--登录尝试登录失败" % account)
                        break
    return wrapper

@auth
def login(*args,**kwargs):
    account = args[0]
    print("*****************************")
    print("  欢迎我行尊贵的用户,%s" % account)
    print("*****************************")
    logging.info("%s--登录成功" % account)
    return account

def transfer_account(*args, **kwargs):
    """从信用卡额度转账到普通储蓄卡中
    1.不校验银行卡号，可随意输入
    2.校验剩余额度与转账金额之间的大小关系"""
    re_card = input("请输入收款账号：").strip()
    money = int(input("请输入转账金额"))
    with open('account_info', 'r', encoding='utf-8') as f:
        date = f.read()
        date_user = date.split('\n\n')
        for i,item in enumerate(date_user):
            if args[0] in item:
                line = item.split('    ')
                card_info = line[1].split('|')
                if int(card_info[2]) >= money:
                    card_info[2] = str(int(card_info[2]) - money)+'\n'
                    logging.info("%s--向[%s]转账%s元" %(args[0],re_card,money))
                else:print("余额不足，无法转账")
                line[1] = '|'.join(card_info)
                new_line = '    '.join(line)
                # print(new_line)
                date_user[i]=new_line
        new_date_usr = '\n\n'.join(date_user)
    with open('account_info', 'w', encoding='utf-8') as f:
        f.write(new_date_usr)

def huankuan(*args,**kwargs):
    """信用卡还款功能：
    1.还款金额不能大于欠款"""
    with open('account_info', 'r', encoding='utf-8') as f:
        account_card_info = []
        date = f.read()
        account_list = date.split("\n\n")
        for i,item1 in enumerate(account_list):
            if args[0] in item1:#找到对应账户行
                account_card_info = item1.split('    ')    #输出额度
                for j,item in enumerate(account_card_info):#出去account：dodo
                    if item[0:4] == '1111':#判断是信用卡
                        item = item.replace(' ', '')
                        account_info = item.split('|')
                        print('卡号：%s\n额度：%s\n可用额度：%s' %(account_info[0],account_info[1],account_info[2]))
                        money = int(input("请输入还款金额："))
                        card_info = item.split("|") #信用卡信息626222666646466|800000|8000
                        if money <= int(card_info[1])-int(card_info[2]):

                            card_info[2] = str(int(card_info[2])+money)+'\n'
                            logging.info("%s--信用卡还款%s" %(args[0], money))
                            print("还款成功！")
                            break
                        elif money > int(card_info[1])-int(card_info[2]):
                            print("还款金额大于欠款金额！")
                            break
                account_card_info[j]='|'.join(card_info)
                temp_str = '    '.join(account_card_info)
                # print(account_card_info)['account:dodo\n', '1111110000000|20000|19999']
                account_list[i] = temp_str
                break
        # print(account_list)
        date_new = '\n\n'.join(account_list)
        # print(date_new)
    with open('account_info','w',encoding='utf-8') as f:
        date_new = date_new+'\n\n'
        f.write(date_new)
@auth
def pay(*args,**kwargs):#money = 传值，account = 传值

    """信用卡付款功能：
    1.购物车直接传参数进来！"""
    money = int(kwargs['money'])
    with open('account_info', 'r', encoding='utf-8') as f:
        account_card_info = []
        date = f.read()
        account_list = date.split("\n\n")
        for i,item1 in enumerate(account_list):
            if args[0] in item1:#找到对应账户行
                account_card_info = item1.split('    ')    #输出额度
                for j,item in enumerate(account_card_info):#出去account：dodo
                    if item[0:4] == '1111':#判断是信用卡
                        item = item.replace(' ', '')
                        account_info = item.split('|')
                        # print('卡号：%s\n额度：%s\n可用额度：%s' %(account_info[0],account_info[1],account_info[2]))
                        # money = int(input("请输入付款金额："))#money 自动获取

                        card_info = item.split("|") #信用卡信息626222666646466|800000|8000
                        if money <= int(card_info[2]):
                            card_info[2] = str(int(card_info[2])-money)+'\n'
                            print("付款成功！")
                            logging.info("%s--付款成功--%s元" % (args[0], money))
                            break
                        elif money > int(card_info[2]):
                            print("额度不足！")
                            break
                account_card_info[j]='|'.join(card_info)
                temp_str = '    '.join(account_card_info)
                # print(account_card_info)['account:dodo\n', '1111110000000|20000|19999']
                account_list[i] = temp_str
                break
        # print(account_list)
        date_new = '\n\n'.join(account_list)
        # print(date_new)
    with open('account_info','w',encoding='utf-8') as f:
        f.write(date_new)

def withdraw_cash(*args,**kwargs):
    """提取信用卡中的额度，到普通储蓄卡中
    1.不校验银行卡号，可随意输入"""
    print('您的账户信息如下：')
    with open('account_info','r',encoding='utf-8') as f:
        account_card_info = []
        date = f.read()
        account_list = date.split("\n\n")
        for i,item1 in enumerate(account_list):
            if args[0] in item1:#找到对应账户行
                account_card_info = item1.split('    ')    #输出额度
                for j,item in enumerate(account_card_info):#出去account：dodo
                    if item[0:4] == '1111':#判断是信用卡
                        item = item.replace(' ', '')
                        account_info = item.split('|')
                        print('卡号：%s\n额度：%s\n可用额度：%s' %(account_info[0],account_info[1],account_info[2]))
                        in_card = input("请输入提现收款账号：")
                        money = int(input("提现金额："))
                        card_info = item.split("|") #信用卡信息626222666646466|800000|8000
                        if money <= int(card_info[2]):
                            card_info[2] = str(int(card_info[2])-money)+'\n'
                            print("提现成功！")
                            logging.info("%s--提现%s元" %(args[0],money))
                            break
                        elif money > int(card_info[2]):
                            print("提现额度不足！")
                account_card_info[j]='|'.join(card_info)
                temp_str = '    '.join(account_card_info)
                # print(account_card_info)['account:dodo\n', '1111110000000|20000|19999']
                account_list[i] = temp_str
                break
    # print(account_list)
    date_new = '\n\n'.join(account_list)
    # print(date_new)
    with open('account_info','w',encoding='utf-8') as f:
        f.write(date_new)

def history_log(*args,**kwargs):
    """
    查询用户的所有操作,
    :param args: 
    :param kwargs: 
    :return: 
    """
    print("%s 资金流水日志如下：" %args[0])
    with open('account.log','r',encoding='utf-8')as f:
        for item in f :
            if args[0] in item and '登录' not in item and '额度查询' not in item:
                print(item)


def manage(*args,**kwargs):
    """
    账户管理：
    1.添加卡片，卡片前4位为’1111‘默认是信用卡，会手动输入额度，初始可用额度为全额度
    2.删除卡片，输出账户下所有卡号，根据卡号编号进行删除卡片全部信息
    3.记录添加卡片，删除卡片的操作日志
    """
    manage_choice = input("1-添加新卡片  2-删除卡片  \n请输入您的操作序号：")
    if manage_choice == '1':
        card = input("卡号：")
        with open('account_info', 'r', encoding='utf-8') as f:
            date = f.read()
            date_list = date.split('\n\n')
            for i,item in enumerate(date_list):
                if args[0] in item:
                    if card[0:4] == '1111':  # 判断是信用卡
                        limit_menoy = input("请输入信用卡额度")
                        date_list[i] = item+'\n'+'    '+card+'|'+limit_menoy+'|'+limit_menoy
                    else:
                        date_list[i] = item + '\n' + '    ' + card + '|' + str(0)
            date_new = '\n\n'.join(date_list)
        with open('account_info', 'w', encoding='utf-8') as f:
            f.write(date_new)
            print("卡片添加成功")
            logging.info("%s--账户管理--添加新卡片：%s成功" %(args[0],card))

    elif manage_choice == '2':
        with open('account_info', 'r', encoding='utf-8') as f:
            date = f.read()
            date_list = date.split('\n\n')
            card_list = []
            for i,item in enumerate(date_list):
                if args[0] in item:
                    item_list = item.split('    ')
                    for j, temp in enumerate(item_list):
                        if '|' in temp:temp1 = temp.split('|');card_list.append(temp1[0])
            for i1,item1 in enumerate(card_list,1):
                print(str(i1)+'-'+item1)
            delete_card = int(input("请选择您要删除的卡号编号："))
            card = card_list[delete_card-1]
            date1 = date.split('\n')
            for i,item1 in enumerate(date1):
                temp_item = item1.split('|')
                if temp_item[0].strip() ==  card:
                    remove_card = date1.pop(i)
                    print("卡片【%s】删除成功" %card)
                    logging.info("%s--账户管理--删除卡片信息：%s" % (args[0], remove_card))
                    break
            new_date = '\n'.join(date1)
        with open('account_info', 'w', encoding='utf-8') as f:
            f.write(new_date)
    else:
        print("您的选择有误，请重新输入")

def limit_money(*args,**kwargs):
    """
    查看信用卡账户额度：
        1.先判断对应账户
        2.判断信用卡，信用卡卡号前4位数为‘1111’
        3.查看额度
        4.account_info必须下面空两行！
        5.查询额度记录日志
    """
    logging.info("%s--额度查询" % args[0])
    print("卡号前4位为信用卡固定位【1111】")
    with open('account_info','r',encoding='utf-8') as f:
        account_card_info = []
        while True:
            m = f.readline()
            if args[0] in m:#找到对应账户行
                while m !='\n':
                    account_card_info.append(m)
                    m = f.readline()
                break
    # print(account_card_info)#['account:meme\n', '    1111111111111111111|300000|300000\n', '    626222666646466|800000|8000\n']
    #输出额度
    for item in account_card_info:
        if item[0:8] == '    1111':#判断是信用卡
            item = item.replace(' ','')
            account_info=item.split('|')
            print('卡号：%s\n额度：%s\n可用额度：%s' %(account_info[0],account_info[1],account_info[2]))
    if '    1111' not in str(account_card_info):
        print("未查询到信用卡记录")

def bye(*args,**kwargs):
    """
    退出登录
    记录退出日志
    """
    print("bye-bye")
    logging.info("%s--退出登录" % account)
    dic_state['user_login_state'] = False
    dic_state['username'] = None








if __name__=='__main__':

    login_return = login()
    # print(login_return)#dodo

    if login_return != None:
        dic ={'1':transfer_account,  #转账
              '2':huankuan,  #还款
              '3':pay,  # 付款
              '4':withdraw_cash,  # 提现
              '5':history_log,  # 日志
              '6':manage,  # 管理账户
              '7':limit_money,  # 额度
              '8':'bye',
              }
        # print(login_state)#1
        #主菜单
        while True:
            menu_choice = input("""1-转账
2-还款
3-付款
4-提现
5-查看资金流水
6-管理账户
7-查看信用卡账户额度
8-退出
请输入您的操作序号： """)
            if menu_choice =='8':bye();break
            if menu_choice == '3':
                money = input("付款金额：");
                dic[menu_choice](login_return,money=money)
            elif menu_choice in dic.keys():
                dic[menu_choice](login_return)#账户名
            else:
                print("您的输入有误，请重新选择")
    else:
        print("无法加载菜单，请先登录")


